<template>
  <div class="published-notice-container">
    <!-- 查询表单 -->
    <div class="search-form">
      <el-form :model="searchForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="公告编号">
              <el-input v-model.number="searchForm.id" placeholder="请输入" type="number" clearable @keyup.enter="handleSearch" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="公告标题">
              <el-input v-model="searchForm.title" placeholder="请输入" clearable @keyup.enter="handleSearch" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门">
              <el-select v-model="searchForm.deptId" placeholder="请选择" clearable filterable>
                <el-option v-for="dept in deptOptions" :key="dept.id" :label="dept.name" :value="dept.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发布时间">
              <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" style="text-align: right">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 公告表格 -->
    <div class="notice-table">
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="公告编号" align="center" />
        <el-table-column prop="deptId" label="部门" align="center">
          <template #default="scope">
            {{ getDeptName(scope.row.deptId) }}
          </template>
        </el-table-column>
        <el-table-column prop="title" label="公告标题" min-width="300" />
        <el-table-column prop="publishTime" label="发布时间" min-width="150" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.publishTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button link size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button link size="small" type="warning" @click="handleRevoke(scope.row)">撤销</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size" :total="pagination.total" layout="total, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 查看公告对话框 -->
    <el-dialog v-model="viewDialogVisible" width="50%" align-center>
      <div class="notice-detail-container">
        <h3 class="notice-title">{{ currentNotice.title }}</h3>
        <div class="notice-meta">
          <span class="dept-name">发布部门：{{ currentNotice.deptName }}</span>
          <span class="publish-time" v-if="currentNotice.publishTime">
            发布时间：{{ formatDate(currentNotice.publishTime) }}
          </span>
        </div>
        <el-divider />
        <div class="notice-content" v-html="currentNotice.content"></div>
      </div>
      <template #footer>
        <el-button type="primary" @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>
    
    <script>
import { getAllDepts } from "../../api/dept";
import {
  getPublishedNotices,
  viewNoticeContent,
  changeNoticeStatus,
} from "../../api/notice";

export default {
  name: "PublishedNotice",
  data() {
    return {
      searchForm: {
        id: null,
        title: "",
        deptId: null,
        dateRange: [],
      },
      deptOptions: [],
      tableData: [],
      loading: false,
      pagination: {
        current: 1,
        size: 10,
        total: 0,
      },
      viewDialogVisible: false,
      currentNotice: {
        title: "",
        content: "",
        deptName: "",
        publishTime: null,
      },
    };
  },
  created() {
    this.initData();
  },
  methods: {
    // 初始化数据
    async initData() {
      await this.fetchDepts();
      await this.fetchData();
    },

    // 获取部门列表
    async fetchDepts() {
      try {
        const res = await getAllDepts();
        this.deptOptions = res.result || [];
      } catch (error) {
        console.error("获取部门列表失败:", error);
        this.$message.error("获取部门列表失败");
      }
    },

    // 获取表格数据
    async fetchData() {
      this.loading = true;
      try {
        const [startDate, endDate] = this.searchForm.dateRange || [null, null];

        const params = {
          id: this.searchForm.id || undefined,
          title: this.searchForm.title || undefined,
          deptId: this.searchForm.deptId || undefined,
          startDate: startDate || undefined, // 直接使用已格式化的值
          endDate: endDate || undefined, // 直接使用已格式化的值
          pageNum: this.pagination.current,
          pageSize: this.pagination.size,
        };

        const res = await getPublishedNotices(params);
        this.tableData =
          res.result?.records || res.result?.list || res.result || [];
        this.pagination.total = res.result?.total || res.result?.length || 0;
      } catch (error) {
        console.error("获取公告数据失败:", error);
        this.$message.error("获取公告数据失败");
      } finally {
        this.loading = false;
      }
    },

    // 获取部门名称
    getDeptName(deptId) {
      if (!deptId) return "-";
      const dept = this.deptOptions.find((item) => item.id === deptId);
      return dept ? dept.name : "-";
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return "-";
      return new Date(date).toLocaleString();
    },

    // 查询按钮点击事件
    handleSearch() {
      this.pagination.current = 1;
      this.fetchData();
    },

    // 重置查询条件
    resetSearch() {
      this.searchForm = {
        id: null,
        title: "",
        deptId: null,
        dateRange: [],
      };
      this.pagination.current = 1;
      this.fetchData();
    },

    // 分页大小改变
    handleSizeChange(size) {
      this.pagination.size = size;
      this.fetchData();
    },

    // 当前页改变
    handleCurrentChange(current) {
      this.pagination.current = current;
      this.fetchData();
    },

    // 查看公告
    async handleView(row) {
      try {
        const res = await viewNoticeContent({ id: row.id });
        this.currentNotice = {
          title: res.result.title,
          content: res.result.content,
          deptName: this.getDeptName(res.result.deptId),
          publishTime: this.formatDate(res.result.publishTime),
        };
        this.viewDialogVisible = true;
      } catch (error) {
        console.error("查看公告失败:", error);
        this.$message.error("查看公告失败");
      }
    },

    // 撤销公告
    async handleRevoke(row) {
      try {
        await this.$confirm("确定要撤销该公告吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        await changeNoticeStatus({ id: row.id, status: 2 });
        this.$message.success("撤销成功");
        this.fetchData();
      } catch (error) {
        console.error("撤销失败:", error);
        if (error !== "cancel") {
          this.$message.error("撤销失败");
        }
      }
    },
  },
};
</script>
    
    <style scoped>
.published-notice-container {
  padding: 0 20px;
  height: 95%;
  display: flex;
  flex-direction: column;
}

.search-form {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.notice-table {
  flex: 1;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination {
  text-align: right;
  background: #fff;
  padding: 10px 20px;
  border-radius: 4px;
}

.notice-detail-container {
  padding: 0 20px;
}

.notice-title {
  text-align: center;
  margin-bottom: 16px;
  color: #303133;
  font-size: 20px;
  font-weight: 500;
}

.notice-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  color: #909399;
  font-size: 14px;
}

.notice-content {
  padding: 0 10px;
  line-height: 1.8;
  font-size: 15px;
  color: #606266;
}

.notice-content >>> p {
  margin: 10px 0;
}

.notice-content >>> img {
  max-width: 100%;
  display: block;
  margin: 10px auto;
}
</style>